<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>axios_basic</title>
  <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.27.2/axios.min.js"></script>
</head>
<body>
  <div>
    <title>基本使用</title>
    <button id="btn_get">GET请求</button>
    <button id="btn_post_add">POST请求_ADD</button>
    <button id="btn_post_del">POST请求_DEL</button>
  </div>
<script type="text/javascript">
  const btnGet = document.getElementById('btn_get')
  const btnPostAdd = document.getElementById('btn_post_add')
  const btnPostDel = document.getElementById('btn_post_del')

  axios.defaults.baseURL = 'http://localhost:3100/icloud';
  axios.defaults.headers.post['Content-Type'] = 'application/json';
  // 添加请求拦截器
  axios.interceptors.request.use(function (config) {
    // 在发送请求之前做些什么
    return config;
  }, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
  });

// 添加响应拦截器
  axios.interceptors.response.use(function (response) {
    // 对响应数据做点什么
    return response;
  }, function (error) {
    // 对响应错误做点什么
    return Promise.reject(error);
  });

  btnGet.addEventListener('click', function(){
    axios.request({
      method: 'GET',
      url: '/mock/user/list'
    }).then(response=>{
      console.log("data:", response.data)
    }, error=>{
      console.log(error);
    })
  })

  btnPostAdd.addEventListener('click', function(){
    axios.post('/mock/user/add',
      {
        username:"老王",
        password:"123",
        birthday:"1992-03-21 02:12:32"
      }, {
        headers: {'Content-Type': 'application/json',},
      }
    ).then(response=>{
      console.log("data:", response.data)
    }, error=>{
      console.log(error);
    })
  })

  btnPostDel.addEventListener('click', function(){
    axios.post('/mock/user/del',
      {
        id: 1
      }
    ).then(response=>{
      console.log("data:", response.data)
    }, error=>{
      console.log(error);
    })
  })

</script>
</body>
</html>